    //
//  CarouselViewController.m
//  SecretFolder
//
//  Created by Deepak Kumar on 24/06/12.
//  Copyright 2012 Frog. All rights reserved.
//

#import "CarouselViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "FullImageViewController.h"
#import "AddNoteViewController.h"
#import "Directory.h"
#import "File.h"
#import "Repository.h"
#import "ListViewController.h"
#import "Item.h"

#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

//#define NUMBER_OF_ITEMS 1000
#define NUMBER_OF_VISIBLE_ITEMS (IS_IPAD? 12: 19)
#define ITEM_SPACING 210.0f
#define INCLUDE_PLACEHOLDERS YES

@implementation CarouselViewController
{
    Directory *mDirectory;
    NSMutableArray *mFileArray;
    UITextView *mTextView;
    UIPopoverController *mPopoverController;
}

@synthesize mCarausel, popoverController, mDownloadObjectDictionary, mAddNotePopoverController;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	mFilePath = [NSString new];
	//mFileArray = [NSMutableArray new];
}

- (void) setDirectory:(Directory *)pDirectory
{
    mDirectory = pDirectory;
    mFileArray = [NSMutableArray arrayWithArray:[mDirectory.mFiles allObjects]];
}

- (NSString *) getDocumentsDirectoryForFolder:(NSString *)pFolder
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
	return [documentsDirectory stringByAppendingPathComponent:pFolder];
}

- (IBAction) addPicButton:(UIBarButtonItem *)pButton
{

//	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
//    {
//		UIActionSheet *tAction = [[UIActionSheet alloc] initWithTitle:@"Add images" delegate:self
//						cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Photo Library", @"Camera", nil];
//		[tAction showFromBarButtonItem:pButton animated:YES];
//		[tAction release];
//	}
//	else {
		
		if ([self.popoverController isPopoverVisible]) {
			[self.popoverController dismissPopoverAnimated:YES];
		} else {
			if ([UIImagePickerController isSourceTypeAvailable:
				 UIImagePickerControllerSourceTypeSavedPhotosAlbum])
			{
				UIImagePickerController *imagePicker =
				[[UIImagePickerController alloc] init];
				imagePicker.delegate = self;
				imagePicker.sourceType =
				UIImagePickerControllerSourceTypePhotoLibrary;
				imagePicker.mediaTypes = [NSArray arrayWithObjects:
										  (NSString *) kUTTypeImage,
										  nil];
				imagePicker.allowsEditing = NO;
				
                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
				self.popoverController = [[UIPopoverController alloc]
										  initWithContentViewController:imagePicker];
				
				popoverController.delegate = self;
				
				[self.popoverController 
				 presentPopoverFromBarButtonItem:pButton
				 permittedArrowDirections:UIPopoverArrowDirectionUp
				 animated:YES];
                }
                else
                {
                    [self presentViewController:imagePicker animated:YES completion:^{}];
                }
				
			}
		}	
}

- (IBAction) addNote:(UIBarButtonItem *)pButton
{
//	iPhoto *tPhoto = [mObjectArray objectAtIndex:mCurrentItemIndex];
//    File *tFile;
//    if ([mFileArray count]) {
//     tFile = [mFileArray objectAtIndex:mCurrentItemIndex];
//    }
//    
//    AddNoteViewController *tController = [[AddNoteViewController alloc] initWithNibName:@"AddNoteViewController" bundle:nil];
//    if ([mFileArray count]>mCurrentItemIndex) {
//        [tController setFile:[mFileArray  objectAtIndex:mCurrentItemIndex]];
//    }
//   
////    [tController.mImageView setImage:tPhoto.mImage];
//    [tController.mImageView setImage:tFile.mFilePath];
//	
//    if (IS_IPAD){
//    tController.mPopoverController = mAddNotePopoverController;
//	self.mAddNotePopoverController = [[UIPopoverController alloc]
//							  initWithContentViewController:tController];
//	
//	mAddNotePopoverController.delegate = tController;
//    
//	[self.mAddNotePopoverController 
//	 presentPopoverFromBarButtonItem:pButton
//	 permittedArrowDirections:UIPopoverArrowDirectionDown
//	 animated:YES];
//    }
//    else
//    {
//        [self presentViewController:tController animated:YES completion:^{}];
//    }
	
    if ([mPopoverController isPopoverVisible]) {
        [mPopoverController dismissPopoverAnimated:YES];
    }
    else
    {
	CGRect tFrame ;
    
    NSMutableArray *tPopoverViewElements = [[NSMutableArray alloc] initWithObjects:[[Item alloc] initWithItem:@"Mark As Favorite" mIsSelected:NO],[[Item alloc] initWithItem:@"Hide" mIsSelected:NO],[[Item alloc] initWithItem:@"Add Note" mIsSelected:NO], nil];
    
    ListViewController *tPopOverViewList = [[ListViewController alloc] initWithNibName:@"ListViewController" bundle:Nil];
    [tPopOverViewList setElementArray:tPopoverViewElements];
    if (IS_IPAD) {
        
        mPopoverController = [[UIPopoverController alloc] initWithContentViewController:tPopOverViewList];
       // mPopoverController.delegate = [tPopOverViewList self];
        mPopoverController.delegate = self;
       // tFrame = CGRectMake(pPoint.x, pPoint.y, 220.0, 180.0);
       // [mPopoverController presentPopoverFromRect:tFrame inView:_carousel.viewForBaselineLayout permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
        [mPopoverController
         	 presentPopoverFromBarButtonItem:pButton
         	 permittedArrowDirections:UIPopoverArrowDirectionDown
         	 animated:YES];
        [mPopoverController setPopoverContentSize:CGSizeMake(220.0, 180.0)];
        
    }
    }
}

- (IBAction) fullScreen:(id)pButton
{
//	iPhoto *tPhoto = [mObjectArray objectAtIndex:mCurrentItemIndex];
//
//	FullImageViewController *tImageView = [[FullImageViewController alloc] initWithNibName:@"FullImageViewController" bundle:nil];
//	[self presentViewController:tImageView animated:YES completion:^{
//        
//    }];
//    
//	[tImageView setFullUmageView:tPhoto.mImage];
//
    if ([mFileArray count]) {
        File *tFile = [mFileArray objectAtIndex:mCurrentItemIndex];
        
        FullImageViewController *tImageView = [[FullImageViewController alloc] initWithNibName:@"FullImageViewController" bundle:nil];
        [self presentViewController:tImageView animated:YES completion:^{
            
        }];
        
        [tImageView setFullUmageView:[UIImage  imageWithContentsOfFile:tFile.mFilePath]];

    }
    
}

#pragma mark -
#pragma mark UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == [actionSheet cancelButtonIndex]) {
		return; 
	}
	else if (buttonIndex == 0) {
		UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
		imagePicker.delegate = self;
		imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		imagePicker.mediaTypes = [NSArray arrayWithObjects:(NSString *) kUTTypeImage,
								  nil];
		imagePicker.allowsEditing = NO;        
        [self presentViewController:imagePicker animated:YES completion:^{
            
        }];
        
	}
	else if (buttonIndex == 1) {
		
	}
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	
	[self.popoverController dismissPopoverAnimated:YES];
	
	NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
	[self dismissViewControllerAnimated:YES completion:^{
        
    }];
	
	
	if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
		// UIImagePickerControllerMediaMetadata
//        NSDictionary *tMetaDataDic = [info objectForKey:UIImagePickerControllerMediaMetadata];
//        NSLog(@"%@", tMetaDataDic);
        
        //NSString *tRandomStr = [NSString stringWithFormat:@"img%d.png", arc4random()%100000];
		
        NSManagedObjectContext *tContext = [Repository sharedRepository].context;
        File *tFile = [NSEntityDescription
                                 insertNewObjectForEntityForName:@"File"
                                 inManagedObjectContext:tContext];
        

        
		NSDate *today = [NSDate date];
		NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
		[dateFormat setDateFormat:@"MMddyyyyhh_mm_ss"];
		NSString *dateString = [dateFormat stringFromDate:today];
		NSString *tFilePath = [self getDocumentsDirectoryForFolder:mDirectory.mName];
		NSString *savedImagePath = [tFilePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", dateString]];
        
        
		NSLog(@"savedImagePath:%@", savedImagePath);
		NSData *imageData = UIImagePNGRepresentation(image);
		//NSLog(@"imageData:%d\nPath:%@", [imageData length], savedImagePath);
		
		[imageData writeToFile:savedImagePath atomically:NO];   

        tFile.mName = dateString;
		tFile.mFilePath = savedImagePath;
        tFile.mFileSize = [NSNumber numberWithFloat:[imageData length]];
        
        [mDirectory addMFilesObject:tFile];
        [[Repository sharedRepository].context save:nil];
        
        [self refreshCarausel];

	}
	else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
	{
		// Code here to support video if enabled
	}
}


-(void)image:(UIImage *)image finishedSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
	if (error) {
        UIAlertView *alert = [[UIAlertView alloc]
							  initWithTitle: @"Save failed"
							  message: @"Failed to save image"\
							  delegate: nil
							  cancelButtonTitle:@"OK"
							  otherButtonTitles:nil];
        [alert show];
	}
}

- (void) refreshCarausel
{
    mFileArray = [NSMutableArray arrayWithArray:[mDirectory.mFiles allObjects]];
    
	[NSTimer scheduledTimerWithTimeInterval:0.4 target:self.mCarausel selector:@selector(reloadData) userInfo:nil repeats:NO];
	//[self.mCarausel reloadData];
}

#pragma mark -
#pragma mark iCarousel methods

- (float)carouselItemWidth:(iCarousel *)carousel
{
    //slightly wider than item view
    return 560.0f;
}

- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
	return [mFileArray count];
}

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index
{
	mCurrentItemIndex = index;
	
	UIView *tView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 532, 404)];
	tView.backgroundColor = [UIColor whiteColor];
	UIImageView *tImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10.0f, 10.0f, 512.0f, 384.0f)];
    tImageView.contentMode = UIViewContentModeScaleAspectFill;
    tImageView.clipsToBounds = YES;
    
	File *tFile = [mFileArray objectAtIndex:index];
    [tImageView setImage:[UIImage  imageWithContentsOfFile:tFile.mFilePath]];

	[tView addSubview:tImageView];
	
    /*
	UIImageView *glossyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, -20.0f, 512.0f, 150.0f)];
	[glossyImageView setImage:[UIImage imageNamed:@"bg_glossy.png"]];	
	[glossyImageView setAlpha:0.6];
	[tView addSubview:glossyImageView];
	*/

	//tFileName = [mFilePath stringByAppendingPathComponent:tFileName];
	//NSLog(@"tFileName:%@", tFileName);
	
	return tView;
}

- (BOOL)carouselShouldWrap:(iCarousel *)carousel
{
    //wrap all carousels
    return YES;
}

- (void)carouselCurrentItemIndexUpdated:(iCarousel *)carousel {
    
	mCurrentItemIndex = carousel.currentItemIndex;
	
}


#pragma mark item clicked
- (void)itemClicked :(iCarousel *)_carousel atIndex:(NSUInteger)index atPoint:(CGPoint)pPoint
{
    
    CGRect tFrame ;
    
    NSMutableArray *tPopoverViewElements = [[NSMutableArray alloc] initWithObjects:[[Item alloc] initWithItem:@"Mark As Favorite" mIsSelected:NO],[[Item alloc] initWithItem:@"Hide" mIsSelected:NO],[[Item alloc] initWithItem:@"Add Note" mIsSelected:NO], nil];
    
    ListViewController *tPopOverViewList = [[ListViewController alloc] initWithNibName:@"ListViewController" bundle:Nil];
    [tPopOverViewList setElementArray:tPopoverViewElements];
    if (IS_IPAD) {
        
    mPopoverController = [[UIPopoverController alloc] initWithContentViewController:tPopOverViewList];
    mPopoverController.delegate = [tPopOverViewList self];
    tFrame = CGRectMake(pPoint.x, pPoint.y, 220.0, 180.0);
    [mPopoverController presentPopoverFromRect:tFrame inView:_carousel.viewForBaselineLayout permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
    [mPopoverController setPopoverContentSize:CGSizeMake(220.0, 180.0)];
    
    }
    else
    {
        UINavigationController *tController =[[ UINavigationController alloc] initWithRootViewController:tPopOverViewList];
        tController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:self action:nil];
        //[tController.view addSubview:tPopOverViewList.view];
       [self presentViewController:tController animated:YES completion:^{}];
    }
//    File *tFile = [mFileArray objectAtIndex:index];
//
//    FullImageViewController *tImageView = [[FullImageViewController alloc] initWithNibName:@"FullImageViewController" bundle:nil];
//	[self presentViewController:tImageView animated:YES completion:^{
//        
//    }];
//
//	[tImageView setFullUmageView:[UIImage  imageWithContentsOfFile:tFile.mFilePath]];
}

- (IBAction) segmentedControlChange:(UISegmentedControl *)pSegmentedControl
{
	[UIView beginAnimations:nil context:nil];
	
	if (pSegmentedControl.selectedSegmentIndex == 0) {
		mCarausel.type = iCarouselTypeLinear;
	}
	else if (pSegmentedControl.selectedSegmentIndex == 1) {
		mCarausel.type = iCarouselTypeRotary;
	}
	else if (pSegmentedControl.selectedSegmentIndex == 2) {
		mCarausel.type = iCarouselTypeCylinder;
	}
	else if (pSegmentedControl.selectedSegmentIndex == 3) {
		mCarausel.type = iCarouselTypeCoverFlow;
	}
	
	[UIView commitAnimations];

}


- (void) startDownloadFile:(iPhoto *)pPhoto forIndexPath:(NSIndexPath *)indexPath
{
	if (!mDownloadObjectDictionary) {
        mDownloadObjectDictionary = [NSMutableDictionary dictionary];
    }
    NSLog(@"In mFiledownloadURL %@",pPhoto.mFileURL);
	
	FileDownloader *fileDownloader = [mDownloadObjectDictionary objectForKey:pPhoto.mFileURL];    
    if (fileDownloader == nil) 
    {
		fileDownloader = [FileDownloader new];
		fileDownloader.mDelegate = self;
		fileDownloader.mIndexPath = indexPath;
		fileDownloader.mPhoto = pPhoto;
		[fileDownloader startDownloadWithFileURL:pPhoto.mFileURL];
		[mDownloadObjectDictionary setObject:fileDownloader forKey:pPhoto.mFileURL];
	}
	else {
	}
	
}

#pragma mark -
#pragma mark FileDownloaderDelegate
- (void) fileDownloader:(FileDownloader *)pFileDownloader photo:(iPhoto *)pPhoto indexPath:(NSIndexPath *)pIndexPath
{
	NSLog(@"FileDownloadStatus");
	[mCarausel removeItemAtIndex:pIndexPath.row animated:NO];
	[mCarausel insertItemAtIndex:pIndexPath.row animated:NO];

}



- (IBAction) backButton:(id)pButton
{
    if ([self.popoverController isPopoverVisible]) {
        [self.popoverController dismissPopoverAnimated:YES];
    }
    
	self.mCarausel.dataSource = nil;
	self.mCarausel.delegate = nil;
	
	[self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return UIInterfaceOrientationIsLandscape(interfaceOrientation)? YES : NO;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
	self.mCarausel = nil;
	self.popoverController = nil;

}


@end
